import datetime

from django.utils.translation import gettext_lazy as _
from django.forms import Form, ModelForm, TextInput, Textarea, DateInput, CheckboxInput, SelectMultiple, \
    Select, NumberInput, EmailInput, HiddenInput, FileInput, IntegerField, CharField, \
    ModelMultipleChoiceField, ModelChoiceField, TimeInput, DateTimeInput
from django.contrib.auth.models import Group, Permission
from django.utils import timezone
from .models import *


class TbModelForm(ModelForm):

    def __init__(self, *args, **kwargs):
        super(TbModelForm, self).__init__(*args, **kwargs)
        if self.fields:
            for k, v in self.fields.items():
                v.widget.attrs.update({'class': 'form-control'})
                if isinstance(v.widget, DateTimeInput):
                    v.widget.attrs.update(
                        {'class': 'form-control', 'type': 'datetime', 'value': str(timezone.now())[:19]})
                if isinstance(v.widget, DateInput):
                    v.widget.attrs.update(
                        {'class': 'form-control', 'type': 'date', 'value': datetime.datetime.today().strftime('%Y-%m-%d')})
                if isinstance(v.widget, Select):
                    v.widget.attrs.update(
                        {'class': 'selectpicker show-tick form-control', 'data-live-search': 'true'})
                if isinstance(v.widget, TimeInput):
                    v.widget.attrs.update(
                        {'class': 'form-control', 'value': str(timezone.localtime())[11:16], 'type': 'datetime'})
                if isinstance(v.widget, Textarea):
                    v.widget.attrs.update({'class': 'form-control summernote'})
                if isinstance(v.widget, CheckboxInput):
                    v.widget.attrs.update({'type': 'checkbox'})

    def save(self, commit=True):
        return super(TbModelForm, self).save(commit)


class OrderForm(TbModelForm):
    class Meta:
        model = Order
        exclude = ['total_price', 'total_discount', 'received', 'is_active', 'price_all_final', 'order_file',
                   'order_file_c', 'datetime_created', 'datetime_updated', 'cooperators']


class OrderUpdateForm(TbModelForm):
    class Meta:
        model = Order
        exclude = ['total_price', 'total_discount', 'received', 'is_active', 'price_all_final', 'order_file',
                   'order_file_c', 'created_by', 'cooperators', 'datetime_created', 'datetime_updated']


class OrderFileUpdateForm(TbModelForm):
    class Meta:
        model = Order
        fields = ['order_code', 'order_desc', 'order_file', 'order_file_c']
        widgets = {
            'order_code': TextInput(attrs={'class': 'form-control', 'readonly': 'readonly'}),
            'order_desc': TextInput(attrs={'class': 'form-control', 'readonly': 'readonly'}),
        }


class OrderEditorUpdateForm(TbModelForm):
    class Meta:
        model = Order
        fields = ['created_by', 'cooperators']
        labels = {
            'cooperators': _('参与人员'),
        }


class EquipmentForm(TbModelForm):
    class Meta:
        model = Equipment
        exclude = ['is_active', 'datetime_created', 'datetime_updated', 'equipment_code_auto']
        widgets = {
            'equipment_para_en': Textarea(attrs={'class': 'summernote'}),
            'equipment_para_cn': Textarea(attrs={'class': 'summernote'}),
            'length': NumberInput(attrs={'class': 'form-control', 'placeholder': _('长/mm')}),
            'width': NumberInput(attrs={'class': 'form-control', 'placeholder': _('宽/mm')}),
            'height': NumberInput(attrs={'class': 'form-control', 'placeholder': _('高/mm')}),
            'equipment_notes': Textarea(attrs={'class': 'summernote'}),
        }


class EquipmentUpdateForm(TbModelForm):
    class Meta:
        model = Equipment
        exclude = ['cost', 'basic_price', 'dist_price', 'is_active', 'datetime_created', 'datetime_updated',
                   'equipment_code_auto']
        widgets = {
            'equipment_para_en': Textarea(attrs={'class': 'summernote'}),
            'equipment_para_cn': Textarea(attrs={'class': 'summernote'}),
            'length': NumberInput(attrs={'class': 'form-control', 'placeholder': _('长/mm')}),
            'width': NumberInput(attrs={'class': 'form-control', 'placeholder': _('宽/mm')}),
            'height': NumberInput(attrs={'class': 'form-control', 'placeholder': _('高/mm')}),
        }


class ClientForm(TbModelForm):
    class Meta:
        model = Client
        exclude = ['is_active', 'datetime_created', 'datetime_updated']


class ItemListForm(TbModelForm):
    class Meta:
        model = ItemList
        exclude = ['is_active', 'datetime_created', 'datetime_updated']


class ItemListNoteUpdateForm(TbModelForm):
    class Meta:
        model = ItemList
        fields = ['equipment_notes', 'created_by']


class ServiceRecordForm(TbModelForm):
    class Meta:
        model = ServiceRecord
        exclude = ['datetime_created', 'datetime_updated']


class AnnounceForm(TbModelForm):
    class Meta:
        model = Announce
        exclude = ['datetime_created', 'datetime_updated']
        widgets = {
            'title': TextInput(attrs={'class': 'form-control'}),
            'announce_tag': SelectMultiple(attrs={'class': 'form-control'}),
            'remarks': Textarea(attrs={'class': 'summernote'}),
            'is_show': CheckboxInput(),
            'created_by': HiddenInput(),
        }


class BatchEquipmentAddForm(Form):
    batch_equipment = IntegerField()

    class Meta:
        labels = {
            'batch_equipment': _('设备列表'),
        }
        widgets = {
            'created_by': HiddenInput(),
        }


class BatchEquipmentCreateForm(Form):
    title = CharField(max_length=100)
    order_list = IntegerField()

    class Meta:
        labels = {
            'title': _('名称'),
        }
        widgets = {
            'title': TextInput(attrs={'class': 'form-control'}),
        }


class EquipmentListForm(TbModelForm):
    class Meta:
        model = EquipmentList
        exclude = ['datetime_created', 'datetime_updated']
        labels = {
            'equipment_list': '设备列表'
        }


class EquipmentPriceUpdateForm(TbModelForm):
    class Meta:
        model = Equipment
        fields = ['equipment_code', 'equipment_en', 'equipment_cn', 'cost', 'basic_price', 'dist_price']


class UserUpdateForm(TbModelForm):

    def __init__(self, *args, **kwargs):
        super(self.__class__, self).__init__(*args, **kwargs)
        self.fields['groups'] = ModelMultipleChoiceField(
            queryset=Group.objects.filter(permissions__content_type__app_label=app_name).distinct(),
            required=True,
            label=_('权限分组'),
            error_messages={'required': "以下是必填项"},
            widget=SelectMultiple(
                attrs={'class': 'form-control'}),
        )

    class Meta:
        model = User
        fields = ['username', 'first_name', 'last_name', 'email', 'groups', 'is_active']
        labels = {
            'email': 'E-mail',
        }


class GroupForm(TbModelForm):

    def __init__(self, *args, **kwargs):
        super(self.__class__, self).__init__(*args, **kwargs)
        self.fields['permissions'] = ModelMultipleChoiceField(
            queryset=Permission.objects.filter(content_type__app_label=app_name).distinct(),
            required=True,
            label=_('权限'),
            error_messages={'required': "以下是必填项"},
            widget=SelectMultiple(
                attrs={'class': 'form-control'}),
        )

    class Meta:
        model = Group
        fields = ['name', 'permissions']
        widgets = {
            'name': TextInput(attrs={'class': 'form-control',
                                     'value': '{0}-staff'.format(app_name),
                                     'placeholder': '{0}{1}{2}'.format(_('请以'), app_name, _('开头'))})
        }


class EquipmentInForm(TbModelForm):
    class Meta:
        model = EquipmentIn
        exclude = ['datetime_created', 'datetime_updated']


class EquipmentInUpdateForm(TbModelForm):
    class Meta:
        model = EquipmentIn
        exclude = ['datetime_created', 'datetime_updated', 'equipment']


class EquipmentOutForm(TbModelForm):

    def __init__(self, *args, **kwargs):
        super(self.__class__, self).__init__(*args, **kwargs)
        equipment_in_l = EquipmentIn.objects.values('equipment').annotate(total_in=Sum('amount')).order_by(
            'total_in').distinct()
        ids = list()
        if equipment_in_l:
            for e in equipment_in_l:
                ids.append(e.get('equipment'))
        e_l = Equipment.objects.filter(pk__in=ids)
        self.fields['equipment'] = ModelChoiceField(
            queryset=e_l,
            required=True,
            label=_('设备'),
            error_messages={'required': "以下是必填项"},
            widget=Select(
                attrs={'class': 'selectpicker show-tick form-control', 'data-live-search': 'true'}),
        )

    class Meta:
        model = EquipmentOut
        exclude = ['datetime_created', 'datetime_updated']


class InOutForm(TbModelForm):
    class Meta:
        model = InOut
        exclude = ['datetime_created',  'datetime_updated', 'left_before']


class InOutUpdateForm(TbModelForm):
    class Meta:
        model = InOut
        exclude = ['datetime_created',  'datetime_updated']


class InOutTypeForm(TbModelForm):
    class Meta:
        model = InOutType
        exclude = ['datetime_created',  'datetime_updated']


class FixedAssetsForm(TbModelForm):
    class Meta:
        model = FixedAssets
        exclude = ['datetime_created',  'datetime_updated']


class FixedAssetsTypeForm(TbModelForm):
    class Meta:
        model = FixedAssetsType
        exclude = ['datetime_created',  'datetime_updated']


class FixedAssetsInForm(TbModelForm):
    class Meta:
        model = FixedAssetsIn
        exclude = ['datetime_created',  'datetime_updated']


class FixedAssetsOutForm(TbModelForm):
    class Meta:
        model = FixedAssetsOut
        exclude = ['datetime_created',  'datetime_updated']


class EquipmentAssemblyForm(TbModelForm):
    class Meta:
        model = EquipmentAssembly
        exclude = ['datetime_created',  'datetime_updated', 'cooperators']


class EquipmentAssemblyUpdateForm(TbModelForm):
    class Meta:
        model = EquipmentAssembly
        exclude = ['datetime_created',  'datetime_updated', 'created_by', 'equipment']
        labels = {
            'cooperators': _('参与人员'),
        }


class PlanAssemblyForm(TbModelForm):
    class Meta:
        model = PlanAssembly
        exclude = ['datetime_created',  'datetime_updated']


class AssemblyItemForm(TbModelForm):
    class Meta:
        model = AssemblyItem
        exclude = ['datetime_created',  'datetime_updated']


class AssemblyItemUpdateForm(TbModelForm):
    class Meta:
        model = AssemblyItem
        exclude = ['datetime_created',  'datetime_updated', 'equipment_assembly']